package com.itany.websocket.websocket.interceptor;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.support.HttpSessionHandshakeInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.Map;

//WebSocket拦截器
public class SpringWebSocketInterceptor extends HttpSessionHandshakeInterceptor {

    @Override
    public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {

        ServletServerHttpRequest servletServerHttpRequest= (ServletServerHttpRequest) request;

        HttpServletRequest httpServletRequest=servletServerHttpRequest.getServletRequest();

        HttpSession session=httpServletRequest.getSession();

        String nickname= (String) session.getAttribute("nickname");

        attributes.put("nickname",nickname);

        return super.beforeHandshake(request,response,wsHandler,attributes);
    }
}
